package com.prj.ufdm.auth.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import com.prj.ufdm.auth.dao.SysFunctionDao;
import com.prj.ufdm.auth.model.SysFunction;

/**  
 * 加载权限表中所有权限URL（所有受保护的URL）
 * @author 胡义振  
 * @date 2018年3月23日  
*/
@Service
public class UrlMetaDataSourceImpl implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysFunctionDao sysFunctionDao;
    
    private static final Logger logger = LoggerFactory.getLogger(UrlMetaDataSourceImpl.class);
    
    /**
     * 判断访问的URL是否在权限表中，如果在权限表中，则转给 AccessDecisionManager decide 方法处理
     */
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		
		HashMap<String, Collection<ConfigAttribute>> resourceMap = getAllSysFunctionCollectionMap();
        String url = ((FilterInvocation) object).getRequestUrl();
        int firstQuestionMarkIndex = url.indexOf("?");
        if (firstQuestionMarkIndex != -1) {
            url = url.substring(0, firstQuestionMarkIndex);
        }
        logger.debug("判断URL是否在权限表中(URL:" + url+" ,权限表："+resourceMap+")");
        Iterator<String> ite = resourceMap.keySet().iterator();
        while (ite.hasNext()) {
            String resURL = ite.next();
            if (url.equals(resURL)) {
            	logger.debug("URL（" + url+"） 在权限表中，返回 decide 方法");
                return resourceMap.get(resURL);
            }
        }
        logger.debug("URL（" + url+"）不在权限表中，放行");
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

    /**
     * 获取所有权限
     */
    private HashMap<String, Collection<ConfigAttribute>> getAllSysFunctionCollectionMap() { 
    	HashMap<String, Collection<ConfigAttribute>> resourceMap = new HashMap<>();
    	try
    	{
	        List<SysFunction> sysFunctionList = sysFunctionDao.selectList(null);
	        for(SysFunction sysFunction : sysFunctionList) {
	        	Collection<ConfigAttribute> configCollection = new ArrayList<>();
	        	if(sysFunction.getFunctionUrl()!=null && !sysFunction.getFunctionUrl().equals("") && sysFunction.getFunctionUrl().indexOf("/")!=-1) {
		            ConfigAttribute cfg = new SecurityConfig(sysFunction.getFunctionUrl());
		            configCollection.add(cfg);
		            resourceMap.put(sysFunction.getFunctionUrl(), configCollection);
	        	}
	        }
    	}
    	catch(Exception er) {
    		logger.debug("获取所有权限发生异常");
    		er.printStackTrace();
    	}
        return resourceMap;
    }
    
}
